package org.erepublik.company.thread;

import java.io.File;
import java.util.Date;

import org.erepublik.company.Configuration;
import org.erepublik.company.scanner.CompanyForSaleScanner;
import org.erepublik.company.service.JSONProductService;

public class CompanyForSaleUpdater extends Thread {

    
    String urlToDatabaseDirectory;

    private final int SLEEP_TIME = 1000 * 60;
    private final long UPDATE_FREQUENCY = 1000 * 60 * 60 * 5; // 1 godzina
    String simpleName;
    private long previousScanTime;

    public CompanyForSaleUpdater() {


        this.simpleName = "companyForSale";
        urlToDatabaseDirectory = Configuration.databasePath + "/" + simpleName;
        previousScanTime = getLastScanTime(simpleName);
    }

    /**
     * @return zwraca czas ostatniego skanu (jest on zawarty w naziwe pliku
     *         przechowywujacego produkty)
     */
    public static long getLastScanTime(String simpleName) {

        String url = JSONProductService.getLastProductFile(simpleName);
        if (url == null)
            return 0;

        File file = new File(url);
        long timeStamp = getTimeStampFromFileName(file);
        return timeStamp;
    }

    public static long getTimeStampFromFileName(File file) {
        String[] fileName = file.getName().split("-");
        return Long.parseLong(fileName[0]);
    }

    public static long getTimeStampFromFileName(String file) {
        String[] fileName = file.split("-");
        return Long.parseLong(fileName[0]);
    }

    /**
     * Glowna petla skanera
     */
    public void run() {

        while (true) {
            try {
                Thread.sleep(SLEEP_TIME);
                long scanTime = new Date().getTime();
                System.out.println(simpleName + " updater...");
                long milisecondsSinceScan = scanTime - previousScanTime;
                System.out.print("ostatni skan był ");
                System.out.print(milisecondsSinceScan / (1000 * 60) + " min. ");
                System.out.print((milisecondsSinceScan % (1000 * 60)) / 1000 + " sec. temu ");
                if (milisecondsSinceScan > UPDATE_FREQUENCY) {

                    System.out.println("skanuje " + simpleName + "...");

                    CompanyForSaleScanner.main(null);
    

                    previousScanTime = getLastScanTime(simpleName);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    
    
}
